import { read, utils, writeFile, write } from "xlsx";
import dayjs from 'dayjs';

export default function () {
    let getDataFromExcel = function (file) {
        return new Promise((resolve, reject) => {
            var reader = new FileReader();
            reader.onload = function (e) {
                var data = e.target.result;
                var workbook = read(data, { type: 'binary' });

                var sheetNames = workbook.SheetNames; // 工作表名称集合
                let dataJson = [];
                sheetNames.forEach((element) => {
                    var worksheet2 = workbook.Sheets[element];
                    var jsonArr = utils.sheet_to_json(worksheet2);
                    dataJson.push(jsonArr);
                });
                resolve(dataJson);
            };
            reader.readAsBinaryString(file);
        });
    };

    //时间格式化
    let formatDate = function (numb) {
        //excel中 numb为从1900/01/01开始的天数,Date传入的值为1970/01/01开始的毫秒数所以传入值的时候应该先-25569(1970/01/01在excel中的值)
        numb = Math.floor(numb - 25569);
        let time = new Date(numb * 24 * 60 * 60 * 1000);
        let result = dayjs(time).format('YYYY/MM/DD');
        if (result == 'Invalid Date') {
            result = dayjs().format('YYYY/MM/DD');
        }
        return result;
    };

    /// datas为导出的数据数组
    /// exportOption为对象, 内置三个选项
    //  let exportOption = {
    //      titles: {},
    //      header: [],
    //      hideColumns: [],
    //  };
    /// 1.titles为对象(用于修改表头展示)
    /// 2.header为数组(用于调整列顺序)
    /// 3.hideColumns为数组(用于隐藏列))
    /// fileName为文件名
    let exportDatas = function (datas = [], exportOption = {}, fileName = '1.xlsx') {
        let arr = [];
        for (let i = 0; i < datas.length; i++) {
            arr.push({ ...datas[i] });
        }
        datas = arr;
        //可以修改展示的顺序
        let header = exportOption.header ? exportOption.header : Object.keys(datas[0]);
        // let header = [];
        //展示的名称
        // titles = { A: "AA", B: "BB", C: "CC" };

        //不展示的列
        let hideColumns = exportOption.hideColumns ? exportOption.hideColumns : [];
        //隐藏不需要展示的列
        header = header.filter(item => !hideColumns.includes(item));
        for (let i = 0; i < hideColumns.length; i++) {
            let column = hideColumns[i];
            datas.forEach(item => {
                delete item[column];
            });
        }

        let newData = exportOption.titles ? [exportOption.titles, ...datas] : [...datas];

        let jsonWorkSheet = utils.json_to_sheet(newData, { header, skipHeader: true });


        let workBook = {
            SheetNames: ['Sheet1'], // 表名
            Sheets: {
                'Sheet1': jsonWorkSheet,
            }
        };
        writeFile(workBook, fileName);
    };

    /// 在excel中导出多个表
    /// datas为导出的数据数组
    /// exportOption为数组,其中的对象内置三个选项
    /// 1.titles为对象(用于修改表头展示)
    /// 2.hideColumns为数组(用于隐藏列))
    /// 3.header为数组(用于调整列顺序)
    /// fileName为文件名
    let exportMultipleDatas = function (datas = [], exportOptions = [], fileName = '1.xlsx', sheetNames = []) {
        let arr = [];
        for (let i = 0; i < datas.length; i++) {
            for (let j = 0; j < datas[i].length; j++) {
                if (arr[i])
                    arr[i].push({ ...datas[i][j] });
                else
                    arr[i] = [{ ...datas[i][j] }];
            }
        }
        datas = arr;

        let jsonSheets = getMultipleJsonWorkSheet(datas, exportOptions);
        let workBook = {
            SheetNames: sheetNames, // 表名
            Sheets: {
                // 'Sheet1': jsonWorkSheet,
                // 'sdf': jsonWorkSheet,
            }
        };

        for (let i = 0; i < sheetNames.length; i++) {
            workBook.Sheets[sheetNames[i]] = jsonSheets[i];
        }

        writeFile(workBook, fileName);
    };


    let getMultipleJsonWorkSheet = function (datas, exportOptions) {
        let jsonSheets = [];
        for (let i = 0; i < datas.length; i++) {

            //可以修改展示的顺序
            let header = exportOptions[i].header ? exportOptions[i].header : Object.keys(datas[i][0]);
            // let header = [];
            //展示的名称
            // titles = { A: "AA", B: "BB", C: "CC" };

            //不展示的列
            let hideColumns = exportOptions[i].hideColumns ? exportOptions[i].hideColumns : [];
            //隐藏不需要展示的列
            header = header.filter(item => !hideColumns.includes(item));
            for (let j = 0; j < hideColumns.length; j++) {
                let column = hideColumns[j];
                datas[i].forEach(item => {
                    delete item[column];
                });
            }

            let newData = exportOptions[i].titles ? [exportOptions[i].titles, ...datas[i]] : [...datas[i]];

            let jsonWorkSheet = utils.json_to_sheet(newData, { header, skipHeader: true });
            jsonSheets.push(jsonWorkSheet);
        }
        return jsonSheets;
    };

    /// 在excel中导出多个表(返回BASE64)
    /// datas为导出的数据数组
    /// exportOption为数组,其中的对象内置三个选项
    /// 1.titles为对象(用于修改表头展示)
    /// 2.hideColumns为数组(用于隐藏列))
    /// 3.header为数组(用于调整列顺序)
    /// fileName为文件名
    let getBase64MultipleDatas = function (datas = [], exportOptions = [], fileName = '1.xlsx', sheetNames = []) {
        let arr = [];
        for (let i = 0; i < datas.length; i++) {
            for (let j = 0; j < datas[i].length; j++) {
                if (arr[i])
                    arr[i].push({ ...datas[i][j] });
                else
                    arr[i] = [{ ...datas[i][j] }];
            }
        }
        datas = arr;

        let jsonSheets = getMultipleJsonWorkSheet(datas, exportOptions);
        let workBook = {
            SheetNames: sheetNames, // 表名
            Sheets: {
                // 'Sheet1': jsonWorkSheet,
                // 'sdf': jsonWorkSheet,
            }
        };

        for (let i = 0; i < sheetNames.length; i++) {
            workBook.Sheets[sheetNames[i]] = jsonSheets[i];
        }
        var wopts = {
            bookType: 'xlsx', // 要生成的文件类型
            bookSST: false, // 是否生成Shared String Table，官方解释是，如果开启生成速度会下降，但在低版本IOS设备上有更好的兼容性
            type: 'base64'
        };
        var wbout = write(workBook, wopts);
        return wbout;
    };


    return { getDataFromExcel, formatDate, exportDatas, exportMultipleDatas, getBase64MultipleDatas };
}
